import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { config } from '../../shared/smartadmin.config';

declare var $: any;
@Component({
	selector: 'sa-carrying-number',
	templateUrl: './carrying-number.component.html',
	styleUrls: ['./carrying-number.css']
})
export class CarryingNumberComponent implements OnInit {
	tableData: any[] = []; //table数据
	totalCount: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	carList: any[] = []; //车辆数据
	companyId: string = ''; //公司ID
	companyList: any[] = []; //公司数据
	deviceId: string = ''; //设备ID
	startTime: string = ''; //开始时间
	endTime: string = ''; //结束时间
	carNumber: string = ''; //车牌号
	selectedCompanyId: string = ''; //选中公司ID
	selectedCompanyName: string = ''; //选中公司名称

	fileType: string = 'excel'; //导出文件类型
	modalType: string = '2'; //导出时间模式
	selfTimeList: any = [{
		selfTime: '',
		index: "stime_1",
	}];
	selfTimeInputId: string = ''; //自定义时间段input的id值
	selfTimeData: any = []; //自定义时间段时间校验缓存集合
	startTimeSelected: number;
	endTimeSelected: number;
	difValue: number;
	timeSlot: string = ''; //提交的时间段
	hourList = [{
		index: 0
	}, {
		index: 1
	}, {
		index: 2
	}, {
		index: 3
	}, {
		index: 4
	}, {
		index: 5
	}, {
		index: 6
	}, {
		index: 7
	}, {
		index: 8
	}, {
		index: 9
	}, {
		index: 10
	}, {
		index: 11
	}, {
		index: 12
	}, {
		index: 13
	}, {
		index: 14
	}, {
		index: 15
	}, {
		index: 16
	}, {
		index: 17
	}, {
		index: 18
	}, {
		index: 19
	}, {
		index: 20
	}, {
		index: 21
	}, {
		index: 22
	}, {
		index: 23
	}];

	constructor(private jsonApiService: JsonApiService) {}

	ngOnInit() {
		this.initDate().then(() => this.load());				
		var s_timePicker = document.getElementById('s_timePicker');
		document.onclick = function(e: any) {		
			if(!(e.target.className === 's_input ng-pristine ng-valid ng-touched' || e.target.className === 's_timePicker s_isActive' || e.target.className === 's_title' || e.target.className === 's_lis' || e.target.className === 's_border_box' || e.target.className === 's_time_footer' || e.target.className === 's_arrow' || e.target.className === 'btn btn-primary s_btn_primary')) {
				s_timePicker.className = s_timePicker.className.replace("s_isActive", "");
			}
		}		
	}
	ngOnDestroy() {
		document.onclick = null;
	}
	//刷新
	refresh() {
		this.load();
	}
	//时间转化
	getTime(date) {
		var year = date.getFullYear();
		var month = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1);
		var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
		return year + "-" + month + "-" + day;
	}
	//初始化时间
	initDate() {
		var that = this;
		return new Promise(function(resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(
				() => {
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
						$("#datetimepicker1").datetimepicker({ //时间插件
							format: "yyyy-mm-dd",
							language: "zh-CN",
							autoclose: true,
							minView: 2,
						}).on("changeDate", function(e) {
							var date = e.date;
							var time = that.getTime(date);
							$("#datetimepicker2").datetimepicker("setStartDate", time);
						});
						$("#datetimepicker2").datetimepicker({ //时间插件
							format: "yyyy-mm-dd",
							language: "zh-CN",
							autoclose: true,
							minView: 2,
						}).on("changeDate", function(e) {
							var date = e.date;
							var time = that.getTime(date);
							$("#datetimepicker1").datetimepicker("setEndDate", time);
						});
						//						var date = new Date();
						//						$("#datetimepicker2").val(that.getTime(date));//当前时间
						//						date.setDate(date.getDate() - 7);//设置前一周
						//						$("#datetimepicker1").val(that.getTime(date));
						resolve();
					});
				}
			);
		})
	}
	//查询
	search_data() {
		this.curPage = 1;
		this.load();
	}
	//初始化加载list数据
	load() {
		this.startTime = $("#datetimepicker1").val();
		this.endTime = $("#datetimepicker2").val();
		let timeCheck = common.correctTimeParams(this.startTime, this.endTime, 0);
		if(!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		let reqdata = 'gridPager={"pageSize":' + this.pageSize + ',"nowPage":' + this.curPage + ',"parameters":{"deviceId":"' + this.deviceId + '","startTime":"' + this.startTime + '","endTime":"' + this.endTime + '"}}'
		this.jsonApiService.http("transportNumber/getTransportNumberList", reqdata).subscribe(data => {
			for(let item of data.exhibitDatas) {
				item.weight = common.twoDecimal(item.weight);
			}
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		})
	}
	//删除所选时间
	del_date() {
		this.startTime = '';
		this.endTime = '';
		$("#datetimepicker1").val('').change();
		$("#datetimepicker2").val('').change();
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}
	//文件类型选择
	fileTypeChange(type) {
		this.fileType = type;
	}
	//时间模式类型选择
	modalTypeChange(type) {
		this.modalType = type;
		if(this.modalType === '3') {
			return;
		}
		this.selfTimeList = [{
			selfTime: '',
			index: "stime_1"
		}];
		this.selfTimeInputId = '';
		this.startTimeSelected = null;
		this.endTimeSelected = null;
	}
	activeModal(num) {
		this.modalType = num;
		if(this.modalType === '3') {
			return;
		}
		this.selfTimeList = [{
			selfTime: '',
			index: "stime_1"
		}];
		this.selfTimeInputId = '';
		this.startTimeSelected = null;
		this.endTimeSelected = null;
	}
	//删除自定义时间
	delSelfTime(index) {
		var len = this.selfTimeList.length;
		for(var i = 0; i < len; i++) {
			if(index === this.selfTimeList[i].index) {
				this.selfTimeList.splice(i, 1);
				break;
			}
		}
	}
	//自定义时间输入后失去焦点后的回调函数,主要校验时间数据是否有重叠,避免重叠提交
	timeBlur(data) {
		//		console.log(data,'失去焦点后的时间的数据')
	}
	//添加自定义时间
	addSelfTime() {
		for(let item of this.selfTimeList) {
			if(!item.selfTime) {
				this.jsonApiService.message('有未填写自定义项,请先填写');
				return;
			}
		}
		if(this.selfTimeList.length < 1) {
			var temIndex = 1;
		} else {
			var temIndex = parseInt(this.selfTimeList[this.selfTimeList.length - 1].index.split('_')[1]) + 1;
		}
		var obj = {
			selfTime: '',
			index: "stime_" + temIndex,
		}
		this.selfTimeList.push(obj);
	}
	//自定义时间input点击时间回调
	isShowTimer(id) {
		this.selfTimeInputId = id;
		$('.s_timePicker').toggleClass('s_isActive');
		this.startTimeSelected = null;
		this.endTimeSelected = null;
	}
	//自定义时间取消picker
	cancelTimePicker() {
		this.selfTimeInputId = '';
		this.startTimeSelected = null;
		this.endTimeSelected = null;
		$('.s_timePicker').toggleClass('s_isActive');
	}
	//自定义时间段校验
	validTime(str1, str2) {
		var resultType = '';
		var minStartTime = 24;
		var maxEndtime = 0;
		this.selfTimeData = [];
		var addDifValue = 0; //差值和,判定是否溢出
		if(!str1) {
			this.jsonApiService.message('请选择开始时间');
			return resultType = "empty";
		} else if(!str2) {
			this.jsonApiService.message('请选择结束时间');
			return resultType = "empty";
		}
		if(str1 >= str2) {
			str2 = str2 + 24;
		}
		//对渲染的数据进行整合,提起始时间和结束时间
		for(let item of this.selfTimeList) {
			if(item.selfTime) {
				var temArr = item.selfTime.split(' - ');
				var temEndTime;
				if(temArr[1].indexOf('+') >= 0) {
					temEndTime = parseInt(temArr[1].split('(+')[0]) + 24 + '';
				} else {
					temEndTime = temArr[1];
				}
				let obj = {
					startTime: parseInt(temArr[0]),
					endTime: parseInt(temEndTime)
				}
				this.selfTimeData.push(obj);
			}
		}
		if(this.selfTimeData.length < 1) {
			return resultType = 'Ok';
		}
		for(let item of this.selfTimeData) {
			if(!(str1 >= item.endTime || str2 <= item.startTime)) {
				resultType = 'conflict';
				return resultType;
			}
		}
		for(let item of this.selfTimeData) {
			addDifValue += item.endTime - item.startTime;
			if(item.startTime < minStartTime) {
				minStartTime = parseInt(item.startTime);
			}
			if(item.endTime > maxEndtime) {
				maxEndtime = parseInt(item.endTime);
			}
		}
		if((str2 - str1 + addDifValue) > 24) {
			resultType = 'overflow';
			return resultType;
		}
		if((str2 - minStartTime) > 24 || (maxEndtime - str1) > 24) {
			resultType = 'overflow';
			return resultType;
		}
		return resultType = 'Ok';
	}
	//提交自定义时间picker
	submitTimerSelected() {
		var flag = this.validTime(this.startTimeSelected, this.endTimeSelected);
		if(flag === 'conflict') {
			this.jsonApiService.message('该时间段和已经设定的时间冲突,请重新选择');
			return;
		} else if(flag === 'overflow') {
			this.jsonApiService.message('时间范围小于等于一天(24小时),请重新选择');
			return;
		}
		if(flag === 'empty') {
			return;
		}
		for(let item of this.selfTimeList) {
			if(item.index === this.selfTimeInputId) {
				if(this.startTimeSelected >= this.endTimeSelected) {
					item.selfTime = this.startTimeSelected + ' - ' + this.endTimeSelected + "(+1天)";
				} else {
					item.selfTime = this.startTimeSelected + ' - ' + this.endTimeSelected;
				}
				$('.s_timePicker').toggleClass('s_isActive');
			}
		}
	}
	//时间段选定值点击事件回调
	selectedTime(val, type) {
		if(type === 'start') {
			this.startTimeSelected = val;
		} else if(type === 'end') {
			this.endTimeSelected = val;
		}
	}
	//取消导出
	cancelExport(val) {
		this.selfTimeList = [{
			selfTime: '',
			index: "stime_1"
		}];
		this.modalType = '2';
		this.fileType = 'excel';
		this.selfTimeInputId = '';
		this.startTimeSelected = null;
		this.endTimeSelected = null;
		val.hide();
	}
	//数据导出提交
	exportSubmit(val) {
		this.startTime = $("#datetimepicker1").val();
		this.endTime = $("#datetimepicker2").val();
		if(this.startTime == '' || this.endTime == '') {
			this.jsonApiService.message("起始结束时间不能为空");
			return;
		}
		let timeCheck = common.correctTimeParams(this.startTime, this.endTime, 0);
		if(!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		var url;
		if(this.fileType === 'pdf') {
			url = 'transportNumber/allExportPdf';
		} else if(this.fileType === 'excel') {
			url = 'transportNumber/allExportExcel';
		}
		if(this.modalType === '1') {
			this.timeSlot = "0-8,8-16,16-24";
		} else if(this.modalType === '2') {
			this.timeSlot = "6-18,18-6";
		} else if(this.modalType === '3') {
			var temArr = [];
			this.timeSlot = '';
			for(let item of this.selfTimeList) {
				if(item.selfTime) {
					temArr = item.selfTime.split(' - ');
					if(temArr[1].indexOf('+') >= 0) {
						temArr[1] = temArr[1].split('(+')[0];
					}
					var str = temArr[0] + "-" + temArr[1];
					this.timeSlot += str + ",";
				}
			}
			if(!this.timeSlot) {
				this.jsonApiService.message('导出数据时间段不能为空,请选择时间段');
				return;
			}
			this.timeSlot = this.timeSlot.substring(0, this.timeSlot.length - 1);
		}
		this.startTime = $("#datetimepicker1").val();
		this.endTime = $("#datetimepicker2").val();
		var param = {
			carNumber: this.carNumber,
			startTime: this.startTime,
			endTime: this.endTime,
			timeSlot: this.timeSlot
		}
		common.exprotDataFile(param, 'param', config.BaseURL + url)
	}
	//数据导出
	export_totle(val) {
		this.startTime = $("#datetimepicker1").val();
		this.endTime = $("#datetimepicker2").val();
		if(!this.startTime || !this.endTime) {
			this.jsonApiService.message('请选择导出报表的时间范围');
			return;
		}
		val.show();
	}
	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.load();
	}
	//公司选中回调
	companySelected(data){
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
		this.deviceId = data.deviceId;
		this.carNumber = data.carNumber;
	}
}